package com.seesmic.methodgroups
{
	/*
	Copyright 2007 SEESMIC, Inc
	Licensed under the Apache License, Version 2.0 (the "License"); 
	you may not use this file except in compliance with the License. You may obtain a copy of the License at 
	
	http://www.apache.org/licenses/LICENSE-2.0 
	
	Unless required by applicable law or agreed to in writing, 
	software distributed under the License is distributed on an 
	"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
	See the License for the specific language governing permissions and limitations under the License.
	*/
	
	import com.seesmic.SeesmicService;
	import com.seesmic.ServiceBase;
	import com.seesmic.helper.URLLoaderBase;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLVariables;
	
 
	
	public class MethodGroupHelper
	{
		public function MethodGroupHelper()
			{
			super();
		}
		 
		 
		public static function invokeMethod(service:ServiceBase, 
		callback:Function, endpoint:String, params:Object = null, method:String = "GET"):void
		{
			var request:URLRequest = new URLRequest(SeesmicService.END_POINT + endpoint);
			var vars:URLVariables = new URLVariables();
			for(var i:* in params)
			{
				vars[i] = params[i]
			}
			
			var seesmicService:SeesmicService = service as SeesmicService
		
			/*
			if(seesmicService.sid != null)
			{				
				vars.sid = seesmicService.sid
			}*/
			
			
			
			request.data = vars
			request.method = method
			
			switch(method.toUpperCase())
			{
				case "PUT":
				case "DELETE":
				var overrideHeader:URLRequestHeader = new URLRequestHeader
				(
				 "X-HTTP-METHOD-OVERRIDE",
				 method.toUpperCase()
				 )
				 request.requestHeaders.push(overrideHeader)
				break;
				case "POST":
				vars.client = 'REST';
				break
				
			}
		
 			var loader:URLLoaderBase = new URLLoaderBase();
 		 	
			
			loader.addEventListener(Event.COMPLETE, callback);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, callback)
			loader.addEventListener(IOErrorEvent.IO_ERROR, callback)
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus)
			loader.addEventListener(URLLoaderBase.TIME_OUT, callback)
		 
			
			loader.addEventListener(Event.COMPLETE, removeListener);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, removeListener)
			loader.addEventListener(IOErrorEvent.IO_ERROR, removeListener)
			
			loader.load(request);
			
		}
		
		public static function onHTTPStatus(e:HTTPStatusEvent):void
		{
			trace("HTTP Status" +e.target)
			
			//	removeListener(e)
		}
		
		public static function removeListener(e:Event):void
		{
			var loader:URLLoaderBase = e.target as URLLoaderBase
			loader.removeAllListener()
		}
		 
	}
}